import win32serviceutil
import win32service
import win32event
import servicemanager
import logging
import os
import time

# Setup logging
LOG_FILE = "C:\\service_log.txt"  # Change this to your desired path
logging.basicConfig(
    filename=LOG_FILE,
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s"
)

class PythonWinService(win32serviceutil.ServiceFramework):
    _svc_name_ = "PythonWinService"  # Service name
    _svc_display_name_ = "Python Windows Service Example"  # Display name
    _svc_description_ = "A sample Windows service written in Python that logs start and stop events."

    def __init__(self, args):
        super().__init__(args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        self.running = True

    def SvcStop(self):
        """Called when the service is stopped."""
        logging.info("Service is stopping.")
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
        self.running = False

    def SvcDoRun(self):
        """Called when the service starts."""
        logging.info("Service is starting.")
        servicemanager.LogMsg(
            servicemanager.EVENTLOG_INFORMATION_TYPE,
            servicemanager.PYS_SERVICE_STARTED,
            (self._svc_name_, "")
        )
        self.main()

    def main(self):
        """Main service loop."""
        while self.running:
            logging.info("Service is running.")
            time.sleep(10)  # Replace this with actual tasks

if __name__ == "__main__":
    win32serviceutil.HandleCommandLine(PythonWinService)